package com.ddtech.business.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.course.entity.Course;
import com.ddtech.business.course.entity.CourseChapter;
import com.ddtech.business.course.entity.CourseType;
import com.ddtech.business.course.mapper.CourseMapper;
import com.ddtech.business.course.query.CourseQuery;
import com.ddtech.business.course.service.CourseChapterService;
import com.ddtech.business.course.service.CourseService;
import com.ddtech.business.course.service.CourseTypeService;
import com.ddtech.business.course.vo.CourseVo;
import com.ddtech.business.course.vo.res.CourseVrResVo;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.framework.system.service.DictDetailService;
import com.ddtech.framework.system.service.dto.DictDetailDTO;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseChapterService courseChapterService;

    @Resource
    private  CourseMapper  courseMapper;
    @Autowired
    private CourseTypeService courseTypeService;

    @Autowired
    private DictDetailService dictDetailService;

    @Override
    public Object pageList(CourseQuery courseQuery) {
        IPage<Course> page = this.page(courseQuery.populatePage(), courseQuery.autoWrapper());
        page.getRecords().forEach(item->{
            CourseType courseType = courseTypeService.getById(item.getTypeId());
            if(courseType!=null){
                item.setTypeName(courseType.getLabel());
            }
        });
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object pageListVr(CourseQuery courseQuery) {
        IPage<Map<String, Object>> page = courseMapper.pageListVr(courseQuery.populatePage(), courseQuery);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object pageCourseList(CourseQuery courseQuery) {
        IPage<Map<String, Object>> page = courseMapper.pageCourseList(courseQuery.populatePage(), courseQuery);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object pageCourseListPc(CourseQuery courseQuery) {
        IPage<Map<String, Object>> page = courseMapper.pageCourseListPc(courseQuery.populatePage(), courseQuery);
        List<Map<String, Object>> list= page.getRecords().stream().map((map) -> {
            Object obj=map.get("themeImage");
            if(obj!=null){
                JSONArray array = JSON.parseArray(obj.toString());
                if (array!=null && array.size()>0){
                    JSONObject json=array.getJSONObject(0);
                    map.put("themeImage",json.get("url"));
                }
            }
            return map;
        }).collect(Collectors.toList());
//        list.forEach(map -> {
//            Object obj=map.get("themeImage");
//            if(obj!=null){
//                JSONArray array = JSON.parseArray(obj.toString());
//                if (array!=null && array.size()>0){
//                    JSONObject json=array.getJSONObject(0);
//                    map.put("themeImage",json.get("url"));
//                }
//            }
//        });
        return PageUtil.toPage(list, page.getTotal());
    }

    @Override
    public Object pageCourseListType(CourseQuery courseQuery) {
        courseQuery.setUserId(SecurityUtils.getUserId());
        //IPage<Map<String, Object>> page = courseMapper.pageCourseListType(courseQuery.populatePage(), courseQuery);
        IPage<Map<String, Object>> page = courseMapper.pageCourseList(courseQuery.populatePage(), courseQuery);
        List<Map<String, Object>> list= page.getRecords().stream().map((map) -> {
            Object obj=map.get("themeImage");
            if(obj!=null){
                JSONArray array = JSON.parseArray(obj.toString());
                if (array!=null && array.size()>0){
                    JSONObject json=array.getJSONObject(0);
                    map.put("themeImage",json.get("url"));
                }
            }
            return map;
        }).collect(Collectors.toList());
        return PageUtil.toPage(list, page.getTotal());
    }


    /***
     * description:课程列表查询-PC\移动端,课程搜索
     * @param:  * @param courseQuery
     * @date: 2023-06-13
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object pageCourseListSearch(CourseQuery courseQuery) {
        IPage<Map<String, Object>> page = courseMapper.pageCourseListSearch(courseQuery.populatePage(), courseQuery);
        List<Map<String, Object>> list= page.getRecords().stream().map((map) -> {
            Object obj=map.get("themeImage");
            if(obj!=null){
                JSONArray array = JSON.parseArray(obj.toString());
                if (array!=null && array.size()>0){
                    JSONObject json=array.getJSONObject(0);
                    map.put("themeImage",json.get("url"));
                }
            }
            return map;
        }).collect(Collectors.toList());
        return PageUtil.toPage(list, page.getTotal());
    }

    @Override
    public Object getCourseInfo(String id) {
        JSONObject json = new JSONObject();
        String userId= SecurityUtils.getUserId();
        Map<String, Object> map = courseMapper.getCourseInfo(id,userId);
        if(map!=null){
            Object obj=map.get("themeImage");
            if(obj!=null){
                JSONArray array = JSON.parseArray(obj.toString());
                if (array!=null && array.size()>0){
                    JSONObject json1=array.getJSONObject(0);
                    map.put("themeImage",json1.get("url"));
                }
            }
        }
        //Map<String, Object> collect = courseMapper.getSelfCollect(userId,id);
        //Map<String, Object> mapScore = courseMapper.getCourseGrade(id);
        json.put("course",map);
        //json.put("collect",collect);
        //json.put("courseScore",mapScore);
        BizPreconditions.check(map == null, BusinessEnum.QUERY_ERROR.getMsg());
        List<CourseChapter> courseChapterList = courseChapterService.getChapterList(id);
        json.put("courseChapterList",courseChapterList);
        return json;
    }

    @Override
    public Object getCourseChapter(String id) {
        JSONObject json = new JSONObject();
        List<CourseChapter> courseChapterList = courseChapterService.getChapterList(id);
        json.put("courseChapterList",courseChapterList);
        return courseChapterList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(CourseVo courseVo) {
        Course course = courseVo.getCourse();
        course.init();
        this.saveOrUpdate(course);
        courseChapterService.saveChapter(course, courseVo);
    }

    @Override
    public CourseVrResVo createVr(Course course) {
        course.init();
        this.saveOrUpdate(course);
        CourseVrResVo courseVrResVo =new CourseVrResVo();
        courseVrResVo.setId(course.getId());
        courseVrResVo.setCourseName(course.getCourseName());
        return courseVrResVo;
    }

    @Override
    public void del(String id) {
        Course course = this.getById(id);
        BizPreconditions.check(course == null, BusinessEnum.QUERY_ERROR.getMsg());
        course.baseDelete();
        this.saveOrUpdate(course);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delType(String id){
        DictDetailDTO  dictDetailDTO = dictDetailService.findById(id);
        if(dictDetailDTO!=null){
            dictDetailService.delete(id);
            courseMapper.updateCourseType(dictDetailDTO.getLabel());
        }
    }

    @Override
    public CourseVo info(String id) {
        Course course = this.getById(id);
        BizPreconditions.check(course == null, BusinessEnum.QUERY_ERROR.getMsg());
        List<CourseChapter> courseChapterList = courseChapterService.getChapter(id);
        CourseVo courseVo = new CourseVo();
        courseVo.setCourse(course);
        courseVo.setCourseChapter(courseChapterList);
        return courseVo;
    }
}
